﻿using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.Infrastructure;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartCity.ProcessEngine.Infrastructure.Implement
{
    public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
    {
        private readonly SCDBcontext db;

        public BaseRepository(SCDBcontext db)
        {
            this.db = db;
        }



        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>受影响行数</returns>
        public Task<int> CreateAsync(T entity)
        {
            db.Set<T>().AddAsync(entity);
            return db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量添加实体集合
        /// </summary>
        /// <param name="entities">实体集合</param>
        /// <returns>受影响行数</returns>
        public Task<int> CreateRangeAsync(List<T> entities)
        {
            db.Set<T>().AddRangeAsync(entities);
            return db.SaveChangesAsync();
        }

        /// <summary>
        /// 物理删除,真删
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Task<int> DelAsync(long Id)
        {
           var t =  db.Set<T>().FindAsync(Id);
            db.Set<T>().Remove(t.Result);
            return db.SaveChangesAsync();
        }

        /// <summary>
        /// 查询全部实体表达式
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return   db.Set<T>();
        }
        /// <summary>
        /// 根据id获取单个实体
        /// </summary>
        /// <param name="Id">指定的实体Id</param>
        /// <returns></returns>
        public  async Task<T> GetModel(long Id)
        {
            return await db.Set<T>().FindAsync(Id);
        }
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>受影响行数</returns>
        public Task<int> UpdateAsync(T entity)
        {

            db.Set<T>().Update(entity);
            return db.SaveChangesAsync();
        }

        public Task<int> UpdateRangeAsync(List<T> entities)
        {
            db.Set<T>().UpdateRange(entities);
            return db.SaveChangesAsync();
        }
    }
}
